<!--待审批账单自定义操作-->
<template>
  <div>
    <el-row>
      <!--是否销账图标 querySaleCustomerBillOff-->
      <el-tooltip
        content="全部销账"
        placement="bottom-start"
        effect="light"
        v-if="list[data.id] === 0"
        class="margin-right-xs"
      >
        <img :src="xiaogreenPng" />
      </el-tooltip>
      <el-tooltip
        content="部分销账"
        placement="bottom-start"
        effect="light"
        v-if="list[data.id] < 0"
        class="margin-right-xs"
      >
        <img :src="xiaoyellowPng" />
      </el-tooltip>
      <el-tooltip
        content="没有销账"
        placement="bottom-start"
        effect="light"
        v-if="list[data.id] !== 0 && list[data.id] > 0"
        class="margin-right-xs"
      >
        <img :src="xiaogreyPng" />
      </el-tooltip>
      <!-- 没有请求前-默认没有销账 -->
      <el-tooltip
        content="没有销账"
        placement="bottom-start"
        effect="light"
        v-if="defaults"
        class="margin-right-xs"
      >
        <img :src="xiaogreyPng" />
      </el-tooltip>
      <!--上传水单 status:-1(上传水单并转发-toUploadBillImg，uploadBillImg，batchUploadBillImg )，1:查看水单-viewBillMemo，其他值，上传水单 toUploadBillImg--->
      <el-tooltip
        content="上传水单并转发"
        placement="bottom-start"
        effect="light"
        class="margin-right-xs"
      >
        <el-link
          v-if="data.status === -1"
          icon="el-icon-position"
          :underline="false"
          @click="toUploadBillImg(data.id, data, 1)"
        ></el-link>
      </el-tooltip>
      <el-tooltip
        content="上传水单"
        placement="bottom-start"
        effect="light"
        class="margin-right-xs"
      >
        <el-link
          v-if="data.status !== 1 && data.status !== -1"
          icon="el-icon-upload2"
          :underline="false"
          @click="toUploadBillImg(data.id, data)"
        ></el-link>
      </el-tooltip>
      <el-tooltip
        content="查看水单"
        placement="bottom-start"
        effect="light"
        class="margin-right-xs"
      >
        <el-link
          v-if="data.status === 1"
          icon="el-icon-picture-outline"
          @click="lookUploadBillImg(data.id, data.name)"
          :underline="false"
        ></el-link>
      </el-tooltip>
      <!--申请开票 applyForInvoice flag==2||flag==3 -->
      <el-tooltip
        content="申请开票"
        placement="bottom-start"
        effect="light"
        class="margin-right-xs"
        v-if="flag === 1 || flag === 2 || flag === 3"
      >
        <el-link
          icon="el-icon-document-checked"
          :underline="false"
          @click="applyForInvoice(data.id, data)"
        ></el-link>
      </el-tooltip>

      <!--开发票 flag==1||flag==3 -->
      <el-tooltip
        content="开发票"
        placement="bottom-start"
        effect="light"
        class="margin-right-xs"
        v-if="flag === 1 || flag === 3"
      >
        <el-link
          icon="el-icon-postcard"
          :underline="false"
          @click="toInvoice(data.id, data)"
        ></el-link>
      </el-tooltip>
      <!-- 修改发票状态信息  保存updateInvoiceStatus -->
      <el-tooltip
        content="修改发票状态信息"
        placement="bottom-start"
        effect="light"
        class="margin-right-xs"
      >
        <el-link
          icon="el-icon-edit-outline"
          :underline="false"
          @click="editInvoiceStatus(data.id, data)"
        ></el-link>
      </el-tooltip>
      <!--重命名 renameBill-->
      <el-tooltip
        content="重命名"
        placement="bottom-start"
        effect="light"
        class="margin-right-xs"
      >
        <el-link
          icon="fa fa-wrench"
          @click="rename(data.name, data.id)"
          :underline="false"
        ></el-link>
      </el-tooltip>
      <!--编辑 editDetail-->
      <el-tooltip
        content="编辑"
        placement="bottom-start"
        effect="light"
        class="margin-right-xs"
      >
        <el-link
          icon="el-icon-edit"
          :underline="false"
          @click="editDetail(data.id, data)"
        ></el-link>
      </el-tooltip>
      <!--导出excel账单-->
      <el-tooltip
        content="导出excel账单"
        placement="bottom-start"
        effect="light"
        class="margin-right-xs"
      >
        <el-link
          :underline="false"
          icon="fa fa-file-excel"
          @click="selectExportTemplate(data.id)"
        ></el-link>
      </el-tooltip>
      <!--导出PDF账单-->
      <el-tooltip
        content="导出pdf账单"
        placement="bottom-start"
        effect="light"
        class="margin-right-xs"
      >
        <el-link
          :underline="false"
          icon="fa fa-file-pdf"
          @click="selectExportTemplate(data.id, 'PDF')"
        ></el-link>
      </el-tooltip>
      <el-tooltip
        content="审核中企服账单"
        placement="bottom-start"
        effect="light"
        class="margin-right-xs"
        v-if="flag === 1 && data.enableCesGroupStatus === 1"
      >
        <el-link
          icon="el-icon-finished"
          :underline="false"
          @click="approveCesGroupBill(data.id)"
        />
      </el-tooltip>
      <!--deleteSaleCustomerBillMemo-->
      <el-tooltip
        content="删除账单"
        placement="bottom-start"
        effect="light"
        class="margin-right-xs"
      >
        <el-link
          icon="el-icon-delete"
          :underline="false"
          @click="deleteSaleCustomerBill(data.id)"
          v-if="data.status !== 1"
        />
      </el-tooltip>
    </el-row>
    <!-- 上传水单并转发 -->
    <el-dialog title="编辑" :visible.sync="toUpDialog">
      <el-form :model="toUpForm" label-width="150px" :rules="toUpRules">
        <el-form-item label="账单备注" prop="reamark">
          <el-input
            size="mini"
            v-model="toUpForm.remark"
            clearable
            style="width: 80%"
          />
        </el-form-item>

        <div class="flex">
          <el-form-item label="账单总额">
            <span>{{ money }}</span>
          </el-form-item>
          <el-form-item label="账单余额">
            <span>{{ totalMoney }}</span>
          </el-form-item>
        </div>
        <el-form-item label="已有水单" v-if="isShow">
          <span v-for="(v, i) in saleCustomerBillMemos" :key="i">
            <el-link
              type="primary"
              :underline="false"
              @click="imgOpen(v.memoImgUrl)"
              >水单{{ i + 1 }}
            </el-link>
            <i
              class="el-icon-close margin-right-sm"
              @click="deleteSaleCustomerBillMemo(v.id)"
            ></i>
            <!-- <el-image :src="fileUrl + v.memoImgUrl"></el-image>
            {{ fileUrl + v.memoImgUrl }} -->
          </span>
        </el-form-item>
        <el-row v-for="(item, index) in toUpForm.items" :key="index">
          <el-col :span="8">
            <el-form-item label="水单币种" prop="currency">
              <el-select v-model="item.currency" filterable clearable>
                <el-option
                  v-for="(itm, idx) in currencyMap"
                  :key="idx"
                  :label="itm"
                  :value="itm"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="水单金额" prop="bankStatementAmount">
              <el-input
                size="mini"
                v-model="item.bankStatementAmount"
                style="width: 200px"
              />
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="水单" prop="memoImgUrl">
              <div class="flex">
                <el-input
                  size="mini"
                  style="width: 50%"
                  name="meno"
                  disabled
                  v-model="item.memoImgUrl"
                />

                <el-upload
                  class="flex"
                  action="#"
                  :on-preview="handlePreview"
                  :on-remove="handleRemove"
                  :before-remove="beforeRemove"
                  :http-request="uploadBillImg"
                  multiple
                  :limit="3"
                  :on-exceed="handleExceed"
                  :file-list="fileList"
                >
                  <el-button
                    size="small"
                    type="primary"
                    @click="selectTd(index)"
                    >点击上传</el-button
                  >
                </el-upload>
                <el-link
                  icon="el-icon-plus"
                  :underline="false"
                  class="margin-lr-xl"
                  @click="onAdd(item)"
                ></el-link>
                <el-link
                  icon="el-icon-minus"
                  :underline="false"
                  @click.prevent="removeDomain(item)"
                ></el-link>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer">
        <el-button size="mini" @click="toUpDialog = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="batchUploadBillImg"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <!-- 查看水单 -->
    <el-dialog :title="lookUpTitle + ' 水单'" :visible.sync="lookUpDialog">
      <el-table :data="lookUpData" style="width: 100%" class="text-sm">
        <el-table-column
          label="水单金额"
          prop="bankStatementAmount"
        ></el-table-column>
        <el-table-column label="图片" prop="memoImgUrl">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="imgUrl(scope)"
              >水单{{ scope.$index + 1 }}</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <!-- 重命名 -->
    <el-dialog title="重命名" :visible.sync="renameDialog" width="40%">
      <el-form :model="formData" label-width="25%">
        <el-form-item label="名称" prop="name">
          <el-input
            size="mini"
            style="width: 350px"
            v-model="formData.name"
            clearable
          />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button size="mini" type="primary" @click="renameBill"
          >确定</el-button
        >
      </div>
    </el-dialog>
    <!-- 申请开票 -->
    <el-dialog title="账单信息" :visible.sync="applyDialog">
      <el-form
        :model="applyForm"
        :rules="rules"
        ref="applyForm"
        label-width="30%"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="已开金额" prop="hasopenAccount">
              <el-input
                size="mini"
                disabled
                v-model="applyForm.hasopenAccount"
                style="width: 70%"
              />
            </el-form-item>
            <el-form-item label="申请金额" prop="applyaccount">
              <el-input
                size="mini"
                v-model="applyForm.applyaccount"
                style="width: 70%"
                clearable
              />
            </el-form-item>
            <el-form-item label="电子/纸质" prop="invoicetype">
              <el-select
                size="mini"
                v-model="applyForm.invoicetype"
                style="width: 70%"
                clearable
              >
                <el-option
                  v-for="(v, i) in crmPapSource"
                  :key="i"
                  :value="parseInt(i)"
                  :label="v"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="未开金额" prop="notopenAccount">
              <el-input
                disabled
                size="mini"
                v-model="applyForm.notopenAccount"
                style="width: 70%"
              />
            </el-form-item>
            <el-form-item label="抬头名称" prop="customerInvoice">
              <el-select
                size="mini"
                v-model="applyForm.customerInvoice"
                style="width: 70%"
                clearable
              >
                <el-option
                  v-for="(v, i) in customerInvoiceSource"
                  :key="i"
                  :label="v"
                  :value="parseInt(i)"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="申请备注" prop="invoiceremark">
              <el-input
                type="textarea"
                v-model="applyForm.invoiceremark"
                style="width: 70%"
                placeholder="请填入客户地址等备注信息"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer">
        <el-button size="mini" @click="applyDialog = false">取消</el-button>
        <el-button size="mini" type="primary" @click="submitForm('applyForm')"
          >确定</el-button
        >
      </div>
    </el-dialog>
    <!-- 修改发票状态信息 -->
    <el-dialog title="修改发票状态信息" :visible.sync="editInvoiceStatusDialog">
      <el-form :model="invoiceStatusForm" label-width="30%">
        <el-row>
          <el-col :span="12">
            <el-form-item label="已开金额" prop="hasopenAccount">
              <el-input
                size="mini"
                v-model="invoiceStatusForm.hasopenAccount"
                style="width: 70%"
              />
            </el-form-item>
            <el-form-item label="申请金额" prop="applyaccount">
              <el-input
                size="mini"
                v-model="invoiceStatusForm.applyaccount"
                style="width: 70%"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="未开金额" prop="notopenAccount">
              <el-input
                size="mini"
                v-model="invoiceStatusForm.notopenAccount"
                style="width: 70%"
              />
            </el-form-item>
            <el-form-item label="发票状态" prop="invoicestate">
              <el-select
                size="mini"
                v-model="invoiceStatusForm.invoicestate"
                style="width: 70%"
                clearable
              >
                <el-option
                  v-for="(v, i) in invoicestateMap"
                  :key="i"
                  :label="v"
                  :value="i"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer">
        <el-button size="mini" @click="editInvoiceStatusDialog = false"
          >取消</el-button
        >
        <el-button size="mini" type="primary" @click="updateInvoiceStatus"
          >确定</el-button
        >
      </div>
    </el-dialog>
    <!-- 导出弹窗 -->
    <el-dialog title="导出账单" :visible.sync="exportDialog" width="40%">
      <el-form :model="exportForm" label-width="200px">
        <el-form-item label="文件" prop="fileTemplateId">
          <el-select
            size="mini"
            v-model="exportForm.fileTemplateId"
            style="width: 350px"
            clearable
            filterable
          >
            <el-option
              v-for="(v, i) in statementTemplates"
              :key="i"
              :label="v.fileName"
              :value="v.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button size="mini" @click="exportDialog = false">取消</el-button>
        <el-button size="mini" type="primary" @click="exportTemplate"
          >确定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ajax } from "@/store/yg/common/utils";
import { m } from "@/store/yg/common/local";
import { closeDialog } from "@/utils";
import axios from "axios";
import { untransform } from "@/store/yg/common/uri";
import * as constant from "@/store/yg/common/constant";
import xiaogreenPng from "@/assets/images/xiaogreen.png";
import xiaoyellowPng from "@/assets/images/xiaoyellow.png";
import xiaogreyPng from "@/assets/images/xiaogrey.png";
export default {
  props: ["data"],
  data() {
    return {
      list: {},
      fileUrl: constant.FILE_SERVER,
      lookUpData: [],
      statementTemplates: [],
      isShow: false,
      defaults: true,
      flag: "",
      saleCustomerBillMemos: [], //水单集合
      fileList: [],
      crmPapSource: {},
      customerInvoiceSource: {},
      invoicestateMap: {},
      currencyMap: {},
      exportForm: {
        fileTemplateId: "",
      },
      toUpRules: {
        bankStatementAmount: [
          { required: true, message: "请输入水单金额", trigger: "blur" },
          {
            pattern: /(^[0-9.]{1,100}$)/,
            message: "水单金额不能包含特殊符号",
          },
        ],
      },
      rules: {
        hasopenAccount: [
          { required: true, message: "请输入已开金额", trigger: "blur" },
        ],
        applyaccount: [
          { required: true, message: "请输入申请金额", trigger: "blur" },
        ],
        invoicetype: [
          { required: true, message: "请选择开票类型", trigger: "change" },
        ],
        notopenAccount: [
          { required: true, message: "请输入未开金额", trigger: "blur" },
        ],
        customerInvoice: [
          { required: true, message: "请选择抬头名称", trigger: "change" },
        ],
      },
      toUpForm: {
        remark: "",
        items: [{ bankStatementAmount: "", memoImgUrl: "", currency: "RMB" }],
      },
      formData: { name: "" },
      invoiceStatusForm: {
        hasopenAccount: "",
        notopenAccount: "",
        applyaccount: "",
        invoicestate: "",
      },
      applyForm: {
        hasopenAccount: "",
        notopenAccount: "",
        applyaccount: "",
        invoicetype: "",
        customerInvoice: "",
        invoiceremark: "",
      },
      toUpDialog: false,
      lookUpDialog: false,
      renameDialog: false,
      applyDialog: false,
      exportDialog: false,
      editInvoiceStatusDialog: false,
      xiaogreenPng: xiaogreenPng,
      xiaoyellowPng: xiaoyellowPng,
      xiaogreyPng: xiaogreyPng,
      selectTdIndex: "",
      totalMoney: "",
      money: "",
      lookUpTitle: "",
      formid: "",
      applyId: "",
      invoiceStatusId: "",
      customerId: "",
      saleCustomerBillId: "",
      fileType: "",
      fileName: "", //导出文件名
      fileId: "", //账单id
      memoImgUrl: "",
      isFirst: "",
    };
  },
  mounted() {
    this.querySaleCustomerBillOff();
    this.authority();
  },
  methods: {
    clearTableData() {
      this.tableData = [];
      // this.isTableData = false;
    },
    m(val) {
      return m(val);
    },
    findKey(obj, value, compare = (a, b) => a === b) {
      return Object.keys(obj).find((k) => compare(obj[k], value));
    },
    // 页面权限判断 0-普通用户 1-财务 2-销售 3-超级管理员
    async authority() {
      let res = await ajax("authority", {});
      // console.log(res);
      this.flag = res;
    },
    // 销账状态
    async querySaleCustomerBillOff() {
      // console.log(this.data);
      let res = await ajax("querySaleCustomerBillOff", {
        ids: [this.data.id],
        costType: this.data.costType,
      });
      // console.log(res);
      this.defaults = false;
      this.list = res;
    },
    //
    async approveCesGroupBill(id) {
      let res = await ajax("approveCesGroupBill", {
        id: id,
      });
    },
    // 修改发票状态信息
    async editInvoiceStatus(id, data) {
      this.invoiceStatusId = id;
      let res = await ajax("editInvoiceStatus", {
        id: id,
      });
      console.log(res);
      this.editInvoiceStatusDialog = true;
      this.invoicestateMap = res.invoicestateMap;
      this.invoiceStatusForm.applyaccount = res.saleCustomerBill.applyaccount;
      this.invoiceStatusForm.hasopenAccount =
        res.saleCustomerBill.hasopenAccount;
      this.invoiceStatusForm.notopenAccount =
        res.saleCustomerBill.notopenAccount;
    },
    // 修改发票状态信息-保存
    async updateInvoiceStatus() {
      let res = await ajax("updateInvoiceStatus", {
        id: this.invoiceStatusId,
        hasopenAccount: this.invoiceStatusForm.hasopenAccount,
        notopenAccount: this.invoiceStatusForm.notopenAccount,
        applyaccount: this.invoiceStatusForm.applyaccount,
        invoicestate: this.invoiceStatusForm.invoicestate,
      });
      console.log(res);
      if (res.code === 200) {
        this.$message.success("修改成功");
        this.editInvoiceStatusDialog = false;
        setTimeout(function () {
          closeDialog();
          location.reload();
        }, 2000);
      } else {
        this.$message.error(m(res.message));
      }
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    imgOpen(memoImgUrl) {
      window.open(this.fileUrl + memoImgUrl);
    },
    // 操作上传水单保存水单
    async batchUploadBillImg() {
      let memoArray = [];
      for (let i = 0; i < this.toUpForm.items.length; i++) {
        if (!this.toUpForm.items[i].bankStatementAmount) {
          this.$message.error(`请检查第${i + 1}个水单，金额没有填写`);
          return false;
        } else if (!this.toUpForm.items[i].memoImgUrl) {
          this.$message.error(`请检查第${i + 1}个水单，文件没有上传`);
          return false;
        }

        let obj = {};
        obj["bankStatementAmount"] = this.toUpForm.items[i].bankStatementAmount;
        obj["memoImgUrl"] = this.toUpForm.items[i].memoImgUrl;
        obj["currency"] = this.toUpForm.items[i].currency;
        memoArray.push(obj);
        if (null == this.firstUploadImgUrl) {
          this.firstUploadImgUrl = this.toUpForm.items[i].memoImgUrl;
        }
      }
      if (this.isFirst == 1 && memoArray.length == 0) {
        this.$message.error("请先上传水单");
        return;
      }
      let res = await ajax("batchUploadBillImg", {
        saleCustomerBillId: this.fileId,
        isFirst: this.isFirst,
        remark: this.toUpForm.remark,
        memoArray: memoArray,
      });
      console.log(res);
      if (res.success) {
        this.$message.success("上传成功");
        // setTimeout(function() {
        //   // closeDialog();
        //   location.reload();
        // }, 2000);
        this.toupload();
      } else {
        this.$message.error(m(res.message));
      }
      this.toUpDialog = false;
    },
    // 操作上传水单弹窗上传文件
    uploadBillImg(params, index) {
      const formData = new FormData();
      formData.append("items[]", params.file);
      const action =
        constant.API_SERVER +
        "/api/consume/upload?uri=" +
        untransform(this.$route.params.uri) +
        "&f=uploadBillImg&type=main";
      axios({
        url: action,
        method: "post",
        data: formData,
        headers: {
          "Content-Type": "multipart/form-data",
        },
      }).then((res) => {
        console.log("res :>> ", res);
        console.log(res.data.data.fileUrl);
        if (res.data.code === 200) {
          this.toUpForm.items[this.selectTdIndex].memoImgUrl =
            res.data.data.fileUrl;
        } else {
          this.$message.error(res.data.data.message);
        }
      });
    },
    selectTd(index) {
      this.selectTdIndex = index;
    },
    // 操作上传水单
    async toUploadBillImg(id, data, isFirst) {
      this.toUpForm.items = [{}];
      this.fileList = [];
      this.isShow = false;
      this.saleCustomerBillMemos = [];
      let first = isFirst;
      this.fileId = id;
      let res = await ajax("toUploadBillImg", {
        id: id,
        isFirst: first,
      });
      console.log(res);
      this.toUpDialog = true;
      if (
        res.saleCustomerBillMemos !== undefined &&
        res.saleCustomerBillMemos.length > 0
      ) {
        this.isShow = true;
        this.saleCustomerBillMemos = res.saleCustomerBillMemos;
      }
      this.totalMoney = res.totalRemain;
      this.money = res.totalCost;
      this.toUpForm.remark = res.saleCustomerBill.remark;
      this.isFirst = res.isFirst;

      const attrs = {
        class: "com.tofba.app.client.customer.CustomerBalanceDetailClient",
      };
      let initRes = await ajax("init", {}, attrs);
      console.log(initRes);
      if (!initRes) {
        this.$message.error("初始化页面信息失败，请刷新重试");
        return;
      }
      this.currencyMap = initRes.currencySource;
    },
    // 删除水单后重新请求数据
    async toupload() {
      let res = await ajax("toUploadBillImg", {
        id: this.fileId,
      });
      if (
        res.saleCustomerBillMemos !== undefined &&
        res.saleCustomerBillMemos.length !== 0
      ) {
        this.isShow = true;
        this.saleCustomerBillMemos = res.saleCustomerBillMemos;
      } else {
        this.isShow = false;
      }
      this.totalMoney = res.totalCost;
      this.money = res.totalRemain;
      this.toUpForm.remark = res.saleCustomerBill.remark;
      this.isFirst = res.isFirst;
    },
    // 删除水单
    async deleteSaleCustomerBillMemo(id) {
      let res = await ajax("deleteSaleCustomerBillMemo", { id: id });
      console.log(res);
      if (res.code === 200) {
        this.$message.success("删除成功");
        this.toupload();
      } else {
        this.$message.error(m(res.message));
      }
    },
    onAdd(item) {
      if (item.bankStatementAmount) {
        this.toUpForm.items.push({ bankStatementAmount: "", memoImgUrl: "" });
      } else {
        this.$message.error("请先填写当前水单金额再新增");
      }
    },
    removeDomain(k) {
      var index = this.toUpForm.items.indexOf(k);
      if (index !== -1) {
        this.toUpForm.items.splice(index, 1);
      }
    },
    // 水单
    imgUrl(scope) {
      window.open(this.fileUrl + scope.row.memoImgUrl);
    },
    // 查看水单
    async lookUploadBillImg(id, name) {
      this.lookUpDialog = true;
      this.lookUpTitle = name;
      let res = await ajax("viewBillMemo", {
        id: id,
      });
      console.log(res);
      this.lookUpData = res.billmemos;
    },
    rename(name, id) {
      this.renameDialog = true;
      this.formData.name = name;
      this.formid = id;
    },
    // 重命名
    async renameBill() {
      if (this.formData.name === "") {
        return this.$message.error("名称不能为空");
      }
      let res = await ajax("renameBill", {
        id: this.formid,
        name: this.formData.name,
      });
      console.log(res);
      if (res.code === 200) {
        this.renameDialog = false;
        this.$message.success("修改成功");
        setTimeout(function () {
          // closeDialog();
          location.reload();
        }, 2000);
      } else {
        this.$message.error("修改失败");
      }
    },
    // 申请开票
    async applyForInvoice(id, data) {
      if (data.invoicestate === 20) {
        return this.$message.error("开票中不允许开票");
      }
      this.applyId = id;
      this.customerId = data.customerId;
      let res = await ajax("applyForInvoice", {
        id: id,
      });
      console.log(res);
      if (res.success) {
        this.applyDialog = true;
        this.crmPapSource = res.crmPapSource;
        this.customerInvoiceSource = res.customerInvoiceSource;
        this.applyForm.customerInvoice = res.defaultCustomerInvoice;
        this.applyForm.applyaccount = res.saleCustomerBill.applyaccount;
        this.applyForm.hasopenAccount = res.saleCustomerBill.hasopenAccount;
        this.applyForm.notopenAccount = res.saleCustomerBill.notopenAccount;
        this.applyForm.invoicetype = res.saleCustomerBill.invoicetype;
        this.applyForm.invoiceremark = res.saleCustomerBill.invoiceremark;
      } else {
        this.$message.error(m(res.message));
      }
    },
    submitForm(value) {
      this.$refs[value].validate((valid) => {
        if (valid) {
          this.doApplyForInvoice();
        } else {
          return false;
        }
      });
    },
    // 申请开票保存
    async doApplyForInvoice() {
      let res = await ajax("doApplyForInvoice", {
        id: this.applyId,
        customerId: this.customerId,
        hasopenAccount: this.applyForm.hasopenAccount,
        notopenAccount: this.applyForm.notopenAccount,
        applyaccount: this.applyForm.applyaccount,
        invoiceId: this.applyForm.customerInvoice,
        invoiceremark: this.applyForm.invoiceremark,
        invoicetype: this.applyForm.invoicetype,
      });
      console.log(res);
      if (res.success) {
        this.$message.success(m(res.message));
        this.applyDialog = false;
        // 刷新列表数据
        setTimeout(() => {
          // closeDialog();
          location.reload();
        }, 2000);
      } else {
        this.$message.error(m(res.message));
      }
    },
    // 开发票
    async toInvoice(id, data) {
      if (!data.applyaccount) {
        this.$message.error("申请金额为空,不允许开发票");
        return false;
      }
      let res = await ajax("toInvoice", {
        id: id,
      });
      console.log(res);
      if (res.success) {
        window.open(
          `#/blank/customer__billinvoice__main?id=${id}&customerId=${data.customerId}`
        );
      } else {
        this.$message.error(m(res.message));
      }
    },
    // 导出选择模板
    async selectExportTemplate(id, fileType) {
      this.saleCustomerBillId = id;
      let res = await ajax("selectExportTemplate", {
        saleCustomerBillId: id,
        fileType: fileType,
      });
      console.log(res);
      if (res.success) {
        this.statementTemplates = res.statementTemplates;
        this.fileType = res.fileType;
        this.fileName = res.fileName;
        this.exportDialog = true;
        this.exportForm.fileTemplateId = "";
      } else {
        this.$message.error(m(res.message));
      }
    },
    // 导出账单
    async exportTemplate() {
      let param = {};
      param["saleCustomerBillId"] = this.saleCustomerBillId;
      param["fileTemplateId"] = this.exportForm.fileTemplateId;
      param["fileType"] = this.fileType;
      param["fileName"] = this.fileName;
      let res = await ajax("exportTemplate", param);
      console.log(res);
      if (res.success) {
        window.open(this.fileUrl + res.filePath);
        this.exportDialog = false;
      } else {
        this.$message.error(m(res.message));
      }
    },
    // 编辑
    async editDetail(id, data) {
      if (this.list[id] === 0) {
        this.$message.error("已销账不允许再编辑");
        return false;
      }
      let customerId = data.customerId;
      let res = await ajax("editDetail", {
        id: id,
      });
      console.log(res);
      window.open(
        `#/blank/customer__balancedetail__main?id=${id}&customerId=${customerId}`
      );
    },
    // 删除
    deleteSaleCustomerBill(id) {
      this.$confirm("确定删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true,
      })
        .then(() => {
          ajax("deleteSaleCustomerBillById", { id: id }).then(
            (res) => {
              console.log(res);
              if (res.code !== 200) {
                this.$message.error(m(res.message));
              } else {
                this.$message({
                  type: "success",
                  message: "删除成功!",
                });
                // 刷新列表数据
                setTimeout(function () {
                  // closeDialog();
                  location.reload();
                }, 2000);
              }
            },
            (error) => {
              console.log(error);
            }
          );
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
};
</script>
